#!/bin/bash

# AI对话应用部署脚本

set -e

echo "🚀 开始部署AI对话应用..."

# 检查Docker和Docker Compose
if ! command -v docker &> /dev/null; then
    echo "❌ Docker未安装，请先安装Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down

# 清理旧镜像（可选）
#read -p "🧹 是否清理旧镜像? (y/N): " -n 1 -r
#echo
#if [[ $REPLY =~ ^[Yy]$ ]]; then
#    echo "🧹 清理旧镜像..."
#    docker system prune -f
#    docker image prune -f
#fi

# 构建并启动服务
echo "🏗️ 构建并启动服务..."
docker-compose up --build -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 健康检查
echo "🔍 进行健康检查..."
attempt=1
max_attempts=10

while [ $attempt -le $max_attempts ]; do
    if curl -f http://localhost:8080/api/health > /dev/null 2>&1; then
        echo "✅ 服务启动成功！"
        break
    else
        echo "⏳ 等待服务启动... (尝试 $attempt/$max_attempts)"
        sleep 10
        ((attempt++))
    fi
done

if [ $attempt -gt $max_attempts ]; then
    echo "❌ 服务启动失败，请检查日志"
    docker-compose logs
    exit 1
fi

# 显示服务状态
echo "📊 服务状态:"
docker-compose ps

echo ""
echo "🎉 部署完成！"
echo ""
echo "📱 访问地址:"
echo "   用户端: http://localhost"
echo "   管理后台: http://localhost/admin"
echo "   API文档: http://localhost:8080/api"
echo ""
echo "🔑 默认账户:"
echo "   管理员: admin / admin123"
echo ""
echo "📋 常用命令:"
echo "   查看日志: docker-compose logs -f"
echo "   停止服务: docker-compose down"
echo "   重启服务: docker-compose restart"
echo ""
